package br.edu.ufersa.scrumgame.mbean.converter;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

import br.edu.ufersa.scrumgame.facade.SprintBacklogFacade;
import br.edu.ufersa.scrumgame.modelo.SprintBacklog;

@FacesConverter(value = "sprintBacklogConverter")
@ManagedBean
public class SprintBacklogConverter implements Converter {

	@EJB
	private SprintBacklogFacade sprintBacklogFacade;

	@Override
	public Object getAsObject(FacesContext facesContext, UIComponent component, String submittedValue) {
		
		if (submittedValue == null || submittedValue.length() == 0) {
			return null;
		}
		
		try {
			SprintBacklog sprintBacklog = sprintBacklogFacade.find(Integer.valueOf(submittedValue));
			return sprintBacklog;
		} catch (NumberFormatException e) {
			throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error",
					"Not valid"));
		}
	}

	@Override
	public String getAsString(FacesContext facesContext, UIComponent component, Object value) {
		String retorno;

		if (value instanceof SprintBacklog) {
			SprintBacklog sprintBacklog = (SprintBacklog) value;
			retorno = String.valueOf(sprintBacklog.getId());
		} else {
			retorno = "";
		}

		return retorno;
	}

}
